package ua.edu.nuos.jeetraining2012.cms.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Class for managing locale settings
 */
public class LocaleWrapper {

    /** Set relative to resources catalog path, where ResourceBundles should be stored. */
    final private static String BUNDLE_PREFIX = "bundles/";

    /**
     * Set locale for this session
     *
     * @param language Locale language part
     * @param country  Locale country  part
     */
    public static void setLocale(String language,String country) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("locale",new Locale(language,country));
    }

    /**
     * Return locale used for this session
     *
     * @return current locale
     */
    public static Locale getLocale() {
        Subject subject = SecurityUtils.getSubject();
        Locale locale = (Locale) subject.getSession().getAttribute("locale");
        if (locale == null)
            return new Locale("uk","UA");
        return locale;
    }

    /**
     * Get ResourceBundle by its name <code>bundleName</code>.
     * This method will be use {@link ua.edu.nuos.jeetraining2012.cms.util.LocaleWrapper#getLocale()} as default locale
     * for returned bundle.
     *
     * @param bundleName        Name of resource bundle.
     * @return                  Instance of ResourceBundle.
     */
    public static ResourceBundle getBundle(String bundleName) {
        return getBundle(bundleName, getLocale());
    }

    /**
     * Get ResourceBundle by its name <code>bundleName</code> with locale preset <code>locale</code>.
     *
     * @param bundleName        Name of resource bundle.
     * @param locale            Locale to be used.
     * @return                  Instance of ResourceBundle.
     */
    public static ResourceBundle getBundle(String bundleName, Locale locale) {
        return ResourceBundle.getBundle(BUNDLE_PREFIX + bundleName, locale);
    }
}
